import 'dart:math';

import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';

class ListViewPage extends StatefulWidget {
  @override
  _ListViewPage createState() => _ListViewPage();
}

class _ListViewPage extends State<ListViewPage> {
  static const loadTag = "**loadTag**";
  List<String> words = [loadTag];

  @override
  void initState() {
    super.initState();
  }

  void getData() {
    print('get data start');
    Future.delayed(Duration(seconds: 2)).then((e) {
      for (int i = 0; i < 10; i++) {
        var randomBit = _randomBit(i);
        print(randomBit);
        words.insert(words.length - 1, randomBit);
      }
      print("data load end");
      print(words.toString());
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    Divider divider = Divider(height: 1, color: Colors.black87);
    return Scaffold(
      appBar: AppBar(
        title: Text("ListViewPage"),
      ),
      body: ListView.separated(
          itemBuilder: (context, index) {
            if (words[index] == loadTag) {
              if (index < 100) {
                getData();
                return Center(child: CircularProgressIndicator());
              } else {
                return Center(
                  child: Text("no data"),
                );
              }
              return null;
            } else {
              return ListTile(
                title: Text(words[index]),
              );
            }
          },
          separatorBuilder: (context, index) {
            return divider;
          },
          itemCount: words.length),
    );
  }

  _randomBit(int len) {
    String scopeF = '123456789'; //首位
    String scopeC = '0123456789'; //中间
    String result = '';
    for (int i = 0; i < len; i++) {
      if (i == 1) {
        result = scopeF[Random().nextInt(scopeF.length)];
      } else {
        result = result + scopeC[Random().nextInt(scopeC.length)];
      }
    }
    return result;
  }
}
